package com.hyl.servlet;

import com.hyl.annotation.RequestMapping;

import java.io.File;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * ServletMappingManager
 *
 * @author hyl
 * @date 2025-06-16
 */
public class ServletMappingManager {

    private Map<String,String> mapper = new HashMap<String,String>();


    public  Map<String,String>  loadFile(String packageName) throws ClassNotFoundException { //com.hyl.servlet.impl
        //1、获取包的路径
        String packagePath = packageName.replace(".","/"); //com/hyl/servlet/impl
        //2、获取包的绝对路径
        String packageAbsolutePath = this.getClass().getResource("/").getPath().concat(packagePath); //D:/workspace/idea-workspace/ssm/src/main/java/com/hyl/servlet/impl
        //3、获取包下的所有类
        File file = new File(packageAbsolutePath);
        File[] files = file.listFiles(); //获取包下的所有类
        for (File f : files) {
            //4、获取类名
            String className = f.getName(); //UserServlet.class
            //5、获取类的路径
            String classPath = packageName+"."+className.substring(0,className.lastIndexOf(".")); //com.hyl.servlet.impl.UserServlet
            //6、获取类的所有
            Class clazz = Class.forName(classPath); //获取类的字节码文件
            //7、获取类的所有方法
            Method[] methods = clazz.getMethods(); //获取类的所有方法
            for (Method m : methods) {
                //8、获取方法的注解
                if (m.isAnnotationPresent(RequestMapping.class)) {
                    //9、获取注解的值
                    RequestMapping requestMapping = m.getAnnotation(RequestMapping.class);
                    String value = requestMapping.value(); //获取注解的值
                    //10、将注解的值和方法名存入map中
                    mapper.put(value,classPath+"."+m.getName()); // /user/login => com.hyl.servlet.impl.UserServlet.login
                }
            }

        }
        return mapper;

//        // 初始化方法=>映射关系
//        mapper.put("/user/login",packageName+".UserServlet.login");
//        mapper.put("/user/reg",packageName+".UserServlet.reg");
//        mapper.put("/user/list",packageName+".UserServlet.list");
//
//        mapper.put("/dept/list",packageName+".DeptServlet.list");
//
//        mapper.put("/role/list",packageName+".RoleServlet.list");
//        mapper.put("/role/add",packageName+".RoleServlet.list");
    }
}
